package com.luolc.syllabustest.widget;

import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.GridLayout;
import android.widget.ImageButton;

import com.luolc.syllabustest.R;
import com.luolc.syllabustest.utils.DeviceUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

/**
 * Name:周选择控件
 * Author: WK（wangkun@xjzhicheng.com)
 * Date: 2016-10-11
 * Describe: 可进行周的选择
 */
public class WeekChoiceDialog extends AlertDialog {

    public static final int SINGLE = 1;//单
    public static final int DOUBLE = 2;//双
    public static final int ALL = 3;//全
    public static final int MIX = 4;//全
    private static final int WEEK_COUNT = 25;//一共25周

    public static final int STATE_CHECKED = 0;//被选中状态
    public static final int STATE_UNCHECKED = -1;//未选中状态

    private CheckedTextView mCheckTvSingle;//单周
    private CheckedTextView mCheckTvDouble;//双周
    private CheckedTextView mCheckTvAll;//全周

    private GridLayout mGridLayout;
    private ImageButton mIBtnDelTime;
    private ImageButton mIBtnSaveTime;

    private int mWeekStatus;//控件WeekView状态

    private ArrayList<String> mChoiceDataSource = new ArrayList<>();//选择的数据源

    private CheckedTextView CACHE_checkView;//缓存上次点击View

    private IGetChoiceDataSource mIGetChoiceDataSource;
    private SyllabusClassTimeInfoView.ITimeCheckListener mITimeCheckListener;


    //数据CallBack接口
    public interface IGetChoiceDataSource {
        void onGetData(ArrayList<String> data);
    }

    public WeekChoiceDialog(Context context) {
        super(context);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view_dialog_week);
        initView();
        setUpStatusView();
        onInvalidateUI();
    }

    /**
     * 初始化View
     */
    private void initView() {
        mCheckTvSingle = (CheckedTextView) findViewById(R.id.ctv_single);
        mCheckTvDouble = (CheckedTextView) findViewById(R.id.ctv_double);
        mCheckTvAll = (CheckedTextView) findViewById(R.id.ctv_all);
        mGridLayout = (GridLayout) findViewById(R.id.grid_layout);
        mIBtnDelTime = (ImageButton) findViewById(R.id.ibtn_del_time);
        mIBtnSaveTime = (ImageButton) findViewById(R.id.ibtn_save_time);

        setListener();
    }

    private void setUpStatusView() {
        if (CACHE_checkView != null) {
            CACHE_checkView.setChecked(false);
        }
        switch (mWeekStatus) {
            case SINGLE:
                mCheckTvSingle.setChecked(true);
                CACHE_checkView = mCheckTvSingle;
                break;
            case DOUBLE:
                mCheckTvDouble.setChecked(true);
                CACHE_checkView = mCheckTvDouble;
                break;
            case ALL:
                mCheckTvAll.setChecked(true);
                CACHE_checkView = mCheckTvAll;
                break;
            case MIX:
                break;
        }
    }

    /**
     * 最后点击再做保存[]
     */

    private void setListener() {
        mCheckTvSingle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CheckedTextView localView = (CheckedTextView) v;
                //没有被选中才改变状态
                if (!localView.isChecked()) {
                    setWeekStatus(SINGLE);
                    showWeekViewAndStatusView(null);
                }
            }
        });
        mCheckTvDouble.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CheckedTextView localView = (CheckedTextView) v;
                //没有被选中才改变状态
                if (!localView.isChecked()) {
                    setWeekStatus(DOUBLE);
                    showWeekViewAndStatusView(null);
                }
            }
        });
        mCheckTvAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CheckedTextView localView = (CheckedTextView) v;
                //没有被选中才改变状态
                if (!localView.isChecked()) {
                    setWeekStatus(ALL);
                    showWeekViewAndStatusView(null);
                }
            }
        });
        //格子的点击事件
        int childCount = mGridLayout.getChildCount();
        for (int i = 0; i < childCount; i++) {
            Button localButton = (Button) mGridLayout.getChildAt(i);
            //设置WeekView中每一个View的监听
            localButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Button btn = (Button) v;
                    //---------------判断状态做处理---------------
                    if (btn.getTag() == null) {//选中
                        btn.setTag(STATE_CHECKED);
                        changeViewBgAndSetStatus4Add(btn);
                        add2Container(btn.getText().toString());
                    } else {//取消选中
                        btn.setTag(null);
                        changeViewBgAndSetStatus4Remove(btn);
                        remove4Container(btn.getText().toString());
                    }
                    //对缓存的CheckedView做修改
                    if (CACHE_checkView != null) {
                        if (CACHE_checkView.isChecked()) {
                            CACHE_checkView.setChecked(false);
                        }
                    }
                    //TODO 思考下...
                    setWeekStatus(MIX);
                }
            });
        }

        // 取消事件
        mIBtnDelTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WeekChoiceDialog.this.dismiss();
            }
        });
        // 保存事件
        mIBtnSaveTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ArrayList<String> data = new ArrayList<>();
                //处理选择数据源
                switch (mWeekStatus) {
                    case SINGLE:
                        data.add("单周");
                        mIGetChoiceDataSource.onGetData(data);
                        break;
                    case DOUBLE:
                        data.add("双周");
                        mIGetChoiceDataSource.onGetData(data);
                        break;
                    case ALL:
                        data.add("全周");
                        mIGetChoiceDataSource.onGetData(data);
                        break;
                    case MIX:
                        //做排序
                        Comparator<String> comparator = new Comparator<String>() {
                            @Override
                            public int compare(String lhs, String rhs) {
                                int left = Integer.valueOf(lhs);
                                int right = Integer.valueOf(rhs);
                                return left - right;
                            }
                        };
                        Collections.sort(mChoiceDataSource, comparator);
                        mIGetChoiceDataSource.onGetData(mChoiceDataSource);
                        break;
                }
                //TODO 要去做WeekConflict验证..
                mITimeCheckListener.onCheck();
                WeekChoiceDialog.this.dismiss();
            }
        });
    }

    /*
    *(更据状态)更新中间的WeekView
    */
    private void onInvalidateUI() {
        //更新WeekView之前清空数据缓存和回复出事状态
//        resumeUIAndDataSource();
        //设置监听和相关逻辑
        int childCount = mGridLayout.getChildCount();
        for (int i = 0; i < childCount; i++) {
            Button localButton = (Button) mGridLayout.getChildAt(i);
            //如果输入Choice更新UI
            if (mChoiceDataSource.contains(String.valueOf(i + 1))) {
                changeViewBgAndSetStatus4Add(localButton);
            } else {
                changeViewBgAndSetStatus4Remove(localButton);
            }
        }

    }

    private void invokeSingle() {
        int childCount = WEEK_COUNT;
        for (int i = 0; i < childCount; i++) {
            int position = i + 1;
            if (position % 2 != 0) {//不能被2整除
                add2Container(String.valueOf(position));
            } else {
                remove4Container(String.valueOf(position));
            }
        }
    }

    private void invokeDouble() {
        int childCount = WEEK_COUNT;
        for (int i = 0; i < childCount; i++) {
            int position = i + 1;
            if (position % 2 == 0) {//被2整除
                add2Container(String.valueOf(position));
            } else {
                remove4Container(String.valueOf(position));
            }
        }
    }

    private void invokeAll() {
        int childCount = WEEK_COUNT;
        for (int i = 0; i < childCount; i++) {
            int position = i + 1;
            add2Container(String.valueOf(position));
        }
    }

    /**
     * 回复初始化状态
     */
    private void resumeUIAndDataSource() {
        mChoiceDataSource.clear();
    }

    /**
     * 改变背景并将数据放入数据容器
     *
     * @param btn 点击的View
     */
    private void changeViewBgAndSetStatus4Add(Button btn) {
        btn.setTag(STATE_CHECKED);
        btn.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.bgCourse7));
    }

    private void add2Container(String data) {
        mChoiceDataSource.add(data);
    }

    private void remove4Container(String data) {
        mChoiceDataSource.remove(data);
    }

    /**
     * 回复背景并设置初始标记
     *
     * @param btn 点击的View
     */
    private void changeViewBgAndSetStatus4Remove(Button btn) {
        btn.setTag(null);
        btn.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.style_color_window_background));
    }

    /**
     * 设置数据源
     *
     * @param inData 设置数据
     */
    public void setDataSource(ArrayList<String> inData) {
        if (inData == null) return;
        int size = inData.size();
        if (size == 1) {
            String localWeek = inData.get(0);
            //针对双周
            if ("双周".equals(localWeek)) {
                setWeekStatus(DOUBLE);
            } else if ("单周".equals(localWeek)) {//针对单周
                setWeekStatus(SINGLE);
            } else if ("全周".equals(localWeek)) {
                setWeekStatus(ALL);
            }
        } else if (size > 1) {
            setWeekStatus(MIX);
        }
        showWeekViewAndStatusView(inData);
    }

    /**
     * 展示页面
     */
    private void showWeekViewAndStatusView(ArrayList<String> inData) {
        resumeUIAndDataSource();
        setUpStatusView();
        switch (mWeekStatus) {
            case ALL:
                invokeAll();
                break;
            case SINGLE:
                invokeSingle();
                break;
            case DOUBLE:
                invokeDouble();
                break;
            case MIX:
                //针对混周
                int size = inData.size();
                for (int i = 0; i < size; i++) {
                    String currentWeek = inData.get(i);
                    if (currentWeek.contains("-")) {
                        int localStart = Integer.valueOf(currentWeek.substring(0, currentWeek.indexOf("-")));
                        int localEnd = Integer.valueOf(currentWeek.substring(currentWeek.indexOf("-") + 1, currentWeek.length()));
                        for (int j = localStart; j <= localEnd; j++) {
                            mChoiceDataSource.add(String.valueOf(j));
                        }
                    } else {
                        mChoiceDataSource.add(currentWeek);
                    }
                }
                break;
        }
        onInvalidateUI();
    }



    @Override
    public void show() {
        super.show();
        //设置大小
        getWindow().setLayout(DeviceUtils.dp2px_2(getContext(), 260), DeviceUtils.dp2px_2(getContext(), 404));
    }

    //--------------------------------------Setter,Getter-----------------------------------------


    public int getWeekStatus() {
        return mWeekStatus;
    }

    public void setWeekStatus(int mWeekStatus) {
        this.mWeekStatus = mWeekStatus;
    }

    public void setIGetChoiceDataSourceListener(IGetChoiceDataSource mIGetChoiceDataSource) {
        this.mIGetChoiceDataSource = mIGetChoiceDataSource;
    }

    public void setTimeConflictCheckListener(SyllabusClassTimeInfoView.ITimeCheckListener timeConflictCheck) {
        this.mITimeCheckListener = timeConflictCheck;
    }

    public ArrayList<String> getChoiceDataSource() {
        return mChoiceDataSource;
    }
}
